//
//  HMComposetextView+Extension.swift
//  微博
//
//  Created by 程双岐 on 16/10/7.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

extension HMComposetextView {
    
    var emoticonText: String{
        var result = ""
        self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: []) { (info, range, _) in
            if let attachement = info["NSAttachment"] as? HMTextAttachment{
                let chs = attachement.emoticon?.chs
                result += chs!
            }else{
                let text = self.attributedText.attributedSubstring(from: range).string
                result += text
            }

         
    }
           return result
    }
    
    
    func insertEmoticon(emoticon: HMEmoticon){
        if emoticon.type == "0" {
            //  点击图片表情
            //            let chs = emoticon.chs!
            //
            //            textView.insertText(chs)
            
            let lastAttbutedString = NSMutableAttributedString(attributedString: self.attributedText)
//            let image = UIImage(named: emoticon.path!)
//            
            //            let attachment = HMTextAttachment()
            //            attachment.emoticon = emoticon
            //
            //            let lineHeight = self.font!.lineHeight
            //
            //
            //            attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            //            attachment.image = image
            //
            //            let attributedstr = NSAttributedString(attachment: attachment)
            
            let attributedstr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: self.font!)
            
            
            //            lastAttbutedString.append(attributedstr)
            
            var selectedRange = self.selectedRange
            lastAttbutedString.replaceCharacters(in: selectedRange, with: attributedstr)
            
            lastAttbutedString.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, lastAttbutedString.length))
            self.attributedText = lastAttbutedString
            
            selectedRange.location += 1
            selectedRange.length = 0
            self.selectedRange = selectedRange
            
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            self.delegate?.textViewDidChange?(self)
            
            
        } else {
            //  点击emoji标签
            let emoji = (emoticon.code! as NSString).emoji()
            self.insertText(emoji!)
        }

    }
}
